#!/bin/bash

set -e

NC_REPO="https://download.nextcloud.com/server/releases/"
INSTALL_DIR="/var/www/"
DEPENDENCIES="apache2 apache2-utils libapache2-mod-php mariadb-server php php-mysql php-sqlite3 php-bz2 php-zip php-gd php-xml php-mbstring php-gmp php-intl php-imap php-curl php-cgi unzip wget"
INTERNAL_IP="$(hostname -I)"
INTERNAL_IP=${INTERNAL_IP%?}

function checkRoot()
{
        if [[ "${EUID}" -ne 0 ]]; then
                echo "You need to run this script as root"
                exit 1
        fi
}

function print_some_text()
{
    local NC=$(tput sgr0)
    local GREEN=$(tput setaf 2)
    echo "${GREEN}============================# ${1} #============================${NC}"
}

function do_install()
{
    print_some_text "Updating system and installing dependencies"
    bash -c "sudo apt install -y ${DEPENDENCIES}"
    bash -c "apt update && apt upgrade -y"

    print_some_text 'Answer "yes" to everything'
    bash -c "mysql_secure_installation"

    for str in "latest.tar.bz2" "latest.tar.bz2.sha512"
    do
        if [[ -f ${INSTALL_DIR}${str} ]]; then
            bash -c "rm ${INSTALL_DIR}${str}"
        fi
    done

    bash -c "wget ${NC_REPO}latest.tar.bz2 ${NC_REPO}latest.tar.bz2.sha512 -P ${INSTALL_DIR}"

    FILE_SIG="$(sha512sum ${INSTALL_DIR}latest.tar.bz2 | sed 's/ .*//')"
    if [ "$(cat ${INSTALL_DIR}latest.tar.bz2.sha512 | sed 's/ .*//')" != "$FILE_SIG" ]; then
        echo "File is currupted, aborting..."
        echo $(cat ${INSTALL_DIR}latest.tar.bz2.sha512 | sed 's/ .*//') $FILE_SIG
        exit 1
    else
        print_some_text "File is not corrupted"
    fi

    print_some_text "Unpacking"
    bash -c "tar -xvf ${INSTALL_DIR}latest.tar.bz2 -C ${INSTALL_DIR}"
    bash -c "rm ${INSTALL_DIR}latest.tar.bz2*"

    read -p "Enter nextcloud database username: " NC_DB_USER
    read -p "Enter nextcloud database user password: " NC_DB_PASSWORD
    read -p "Enter nextcloud database name: " NC_DB_NAME

    mysql -u root -e "DROP DATABASE IF EXISTS ${NC_DB_NAME}"
    mysql -u root -e "CREATE DATABASE ${NC_DB_NAME}"
    mysql -u root -e "DROP USER IF EXISTS '${NC_DB_USER}'@'localhost'"
    mysql -u root -e "CREATE USER '${NC_DB_USER}'@'localhost' IDENTIFIED BY '${NC_DB_PASSWORD}'"
    mysql -u root -e "GRANT ALL PRIVILEGES ON ${NC_DB_NAME}.* TO '${NC_DB_USER}'@localhost"
    mysql -u root -e "FLUSH PRIVILEGES"

    bash -c "mkdir -p ${INSTALL_DIR}nextcloud/data"
    bash -c "chown -R www-data:www-data ${INSTALL_DIR}nextcloud/"
    bash -c "chmod 750 ${INSTALL_DIR}nextcloud/data"
    echo 'Alias /nextcloud "'${INSTALL_DIR}'nextcloud/"
<Directory '${INSTALL_DIR}'nextcloud/>
    Require all granted
    AllowOverride All
    Options FollowSymLinks MultiViews
    <IfModule mod_dav.c>
        Dav off
    </IfModule>
</Directory>' > /etc/apache2/sites-available/nextcloud.conf

    bash -c "a2ensite nextcloud.conf"
    bash -c "a2enmod mime headers rewrite dir env"
    bash -c "systemctl start apache2"
    bash -c "systemctl enable apache2"
    bash -c "systemctl reload apache2"

    print_some_text "Go to http://${INTERNAL_IP}/nextcloud in your web browser, make some configuration there and continue configuration here"
    echo "P.S. Use MariaDB"
    read -p "Specify custom data directory? (y/n): " yesno
    case $yesno in
        [Yy]* )
            PREV_DIR=$(cat ${INSTALL_DIR}nextcloud/config/config.php | grep "datadirectory" | sed "s/.*=> '//" | sed "s/'.*//")
            read -p "What directory?: " DIR
            read -p "Do you want to mount a partition there? (y/n): " yesno1
            if [ ! -d "${DIR}" ]; then
                bash -c "mkdir -p ${DIR}"
            fi
            case $yesno1 in
                [Yy]*)
                    bash -c "lsblk"
                    read -p "What device?: " DEV
                    read -p "Would you like to partition it? (y/n): " yesno2
                    case $yesno1 in
                        [Yy]* )
                            bash -c "cfdisk ${DEV}"
                            bash -c "lsblk"
                            read -p "Specify partition you've just created on ${DEV}: " DEV
                            ;;
                    esac
                    read -p "Format partition? (y/n): " sus
                    case $sus in
                    [Yy]* )
                        bash -c "mkfs.ext4 ${DEV}"
                        ;;
                    esac
                    bash -c "mount ${DEV} ${DIR}"

                    bash -c "mv -v ${PREV_DIR} ${DIR}"
                    bash -c "echo '$(blkid ${DEV} --output export | grep UUID= | sed -n 1p)   ${DIR}  ext4    defaults    0 2'"
                    sed -i "/'datadirectory' =>/c\  'datadirectory' => '${DIR}/data'," ${INSTALL_DIR}nextcloud/config/config.php
                    bash -c "touch ${DIR}/data/.ocdata"
                    bash -c "chown -R www-data:www-data ${DIR}/data"
                    ;;
                * )
                    bash -c "mv -v ${PREV_DIR} ${DIR}"
                    bash -c "touch ${DIR}/data/.ocdata"
                    bash -c "chown -R www-data:www-data ${DIR}/data"
                    sed -i "/'datadirectory' =>/c\  'datadirectory' => '${DIR}/data'," ${INSTALL_DIR}nextcloud/config/config.php
                    ;;
            esac
            ;;
    esac

    sed -i "/0 =>/c\    0 => '*.*.*.*'," ${INSTALL_DIR}nextcloud/config/config.php
    sed -i "/upload_max_filesize/c\upload_max_filesize=20480" /etc/php/*/apache2/php.ini
    sed -i "/post_max_size/c\post_max_size=20480" /etc/php/*/apache2/php.ini
    bash -c "systemctl restart apache2"
    print_some_text "Installation done"
}

function set_up_https()
{
    read -p "Set up https? (y/n): " yesno
    case $yesno in
        [Yy]* )
            print_some_text "Generating ssl certificates"
            if [[ ! -d /etc/apache2/certs ]]; then
                bash -c "mkdir /etc/apache2/certs"
            fi
            bash -c "openssl req -new -newkey rsa:4096 -x509 -sha256 -days 365 -nodes -out /etc/apache2/certs/cert.crt -keyout /etc/apache2/certs/key.key"

            print_some_text "Updating apache configuration"
            bash -c "echo \
    '<Directory /var/www/html>
            AllowOverride All
    </Directory>' >> /etc/apache2/apache2.conf"

            bash -c "echo \
    '<VirtualHost *:80>
            RewriteEngine On
            RewriteCond %{HTTPS} !=on
            RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]
    </VirtualHost>
    <VirtualHost *:443>
            ServerAdmin webmaster@localhost
            DocumentRoot /var/www/html
            ErrorLog ${APACHE_LOG_DIR}/error.log
            CustomLog ${APACHE_LOG_DIR}/access.log combined
            SSLEngine on
            SSLCertificateFile /etc/apache2/certs/cert.crt
            SSLCertificateKeyFile /etc/apache2/certs/key.key
    </VirtualHost>' > /etc/apache2/sites-enabled/000-default.conf "

            bash -c "a2enmod ssl"
            bash -c "a2enmod rewrite"
            bash -c "systemctl restart apache2"
            ;;
    esac
}

checkRoot
do_install
set_up_https
